#include <DHT.h>
#include <ESP8266WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

#define DHTPIN D4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "wifi";
const char* password = "password";

IPAddress server_addr(*, *, *, *);
const uint16_t mysql_port = *;
char user[] = "***";
char pass[] = "*****";
char db_name[] = "***";
WiFiClient client;
MySQL_Connection conn((Client *)&client);
bool isConnected = false;

void storeReading(float t, float h) {
    if (isConnected) {
        char query[256];
        MySQL_Cursor *cursor = new MySQL_Cursor(&conn);
        sprintf(query, "INSERT INTO 8266 (client_id, temp, hum) VALUES ('8266',%.2f, %.2f)", t, h);
        cursor->execute(query);
        delete cursor;  // 删除cursor对象以避免内存泄漏
    }
}

void connectToWiFiAndMySQL() {
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }
    digitalWrite(LED_BUILTIN, LOW);
    Serial.println("WiFi connected..!");
    Serial.print("Got IP:");
    Serial.println(WiFi.localIP());

    int connectionAttempts = 0;
    while (connectionAttempts < 5 && !conn.connect(server_addr, mysql_port, user, pass, db_name)) {
        Serial.println("Connection failed. Retrying...");
        delay(10000);
        connectionAttempts++;
    }
    if (connectionAttempts == 5) {
        Serial.println("Failed to connect to MySQL after 5 attempts. Exiting...");
        while (true) {}
    } else {
        isConnected = true;
        Serial.println("Connected to MySQL");
    }
}

void reconnect() {
    isConnected = false;
    conn.close();
    WiFi.disconnect();
    delay(5000);
    connectToWiFiAndMySQL();
}

void setup() {
    dht.begin();
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.begin(9600);
    connectToWiFiAndMySQL();
}

void loop() {
    if (!isConnected) {
        digitalWrite(LED_BUILTIN, HIGH);
        reconnect();
    }

    delay(200);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    if (isnan(h) || isnan(t)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
    }
    Serial.printf("当前湿度：%0.2f%%\n", h);
    Serial.printf("当前温度：%0.2f℃\n", t);
    storeReading(t, h);
    delay(60000);
}